﻿/* Copyright 2012 Sannel Software, L.L.C.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Text;

namespace Sannel.Calculate.Nodes
{
	public class OperatorNode : BaseNode
	{
		public override NodeType NodeType
		{
			get { return Nodes.NodeType.Operator; }
		}

		public OperatorCategory Category
		{
			get;
			protected set;
		}

		public OperatorType Operator
		{
			get;
			protected set;
		}

		public OperatorNode(String @operator)
		{
			if (@operator == null)
			{
				throw new ArgumentNullException("operator");
			}

			switch (@operator.Trim())
			{
				case "++":
					Category = OperatorCategory.Primary;
					Operator = OperatorType.Increment;
					break;

				case "--":
					Category = OperatorCategory.Primary;
					Operator = OperatorType.Decrement;
					break;

				case "+":
					Category = OperatorCategory.Additive;
					Operator = OperatorType.Plus;
					break;

				case "-":
					Category = OperatorCategory.Additive;
					Operator = OperatorType.Minus;
					break;

				case "*":
					Category = OperatorCategory.Multiplicative;
					Operator = OperatorType.Multiply;
					break;

				case "/":
					Category = OperatorCategory.Multiplicative;
					Operator = OperatorType.Division;
					break;

				case "%":
					Category = OperatorCategory.Multiplicative;
					Operator = OperatorType.Modules;
					break;

				default:
					throw new ExpressionParseException(Messages.UnsupportedOperator, @operator);
			}
		}

		public OperatorNode(OperatorCategory operatorCategory, OperatorType operatorType)
		{
			switch (operatorType)
			{
				case OperatorType.Multiply:
					if (operatorCategory != OperatorCategory.Multiplicative)
					{
						throw new ExpressionParseException(Messages.OperatorAndCategoryInvalid, operatorType, operatorCategory);
					}
					break;
			}
			this.Category = operatorCategory;
			this.Operator = operatorType;
		}

		public override BaseNode Copy()
		{
			var node = new OperatorNode(Category, Operator);
			return node;
		}
	}
}
